from api import models
from django.http import JsonResponse
from  rest_framework.views import APIView
from api.utils.auth import create_token
from api.logger import logger
from rest_framework_jwt.utils import jwt_decode_handler



class AuthView(APIView):
    """
    用户登陆认证，生成并保存token
    """
    authentication_classes = []
    def post(self,request,*args,**kwargs):

        ret = {"code": 200, "status": "success", "data": {"token": None}}
        username = request.data.get('username')
        password = request.data.get('password')
        try:
            obj = models.Users.objects.filter(username=username,password=password).first()
            if obj:
                #为用户创建token,如果已存在则更新，否则创建
                token = create_token(obj)
                ret['status'] = 'success'
                ret['data']['token'] = token
            else:
                ret['code'] = 401
                ret['status'] = '用户名或密码错误'
        except Exception as e:
            logger.error(e)
            ret['code'] = 400
            ret['status'] = 'error'
        return JsonResponse(ret)


class AuthInfoView(APIView):
    """
    获取登陆用户信息
    """
    def get(self,request,*args,**kwargs):
        ret = {"code":200,"status":"success","data":{"roles":[],"introduction": '',
        "avatar": 'https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif',
        "name": ''}}
        token = request.META.get('HTTP_AUTHORIZATION')
        try:
            user_info = jwt_decode_handler(token)
            user_obj = models.Users.objects.get(id=user_info['user_id'])
            if user_obj:
                ret['status'] = 'success'
                ret['data']['name'] = user_obj.username
                for i in user_obj.roles.all():
                    ret['data']['roles'].append(i.title)
            else:
                ret['code'] = 401
                ret['status'] = '认证失败'
        except Exception as e:
            logger.error(e)
            ret['code'] = 400
            ret['status'] = 'error'
        return JsonResponse(ret)


class LogoutView(APIView):
    """
    退出登陆
    """
    def post(self,request,*args,**kwargs):
        ret = {"code":200,"status":"success","data":'success'}
        token = request.META.get('HTTP_AUTHORIZATION')
        try:
            obj = models.UserToken.objects.filter(token=token).first()
            if obj:
                obj.delete()
            else:
                ret['code'] = 401
                ret['status'] = '退出失败'
        except Exception as e:
            logger.error(e)
            ret['code'] = 400
            ret['status'] = 'error'
        return JsonResponse(ret)